﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web;
using System.Diagnostics;
using System.Net;
using System.IO;
using System.Threading.Tasks;
using MusicMashup.Models;

namespace MusicMashup.Controllers
{
    public class PlaylistController : ApiController
    {
        private MusicRepository rep;

        public PlaylistController()
        {
            rep = new MusicRepository();
        }

        // Returns a list of all songs in the database, formatted for the musicplayer:
        public List<List<String>> Get()
        {
            IQueryable<Song> songs;
            try
            {
                songs = rep.GetSongs();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                throw new HttpResponseException(ex.Message, HttpStatusCode.InternalServerError);
            }

            if (songs == null)  // No songs found
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            // Build playlist for music player:
            List<List<String>> playlist = new List<List<String>>();

            foreach (var song in songs)
            {
                List<String> entry = new List<String>();
                entry.Add(song.Src);            // entry[0]
                entry.Add(song.Name);           // entry[1]
                entry.Add(song.Id.ToString());  // entry[2]
                playlist.Add(entry);
            }
            return playlist;
        }

        // Return a collection of songs by search query
        public IQueryable<Song> Get(String query)
        {
            IQueryable<Song> songs;

            try
            {
                if (query == "ALL")
                    songs = rep.GetSongs(); // return entire list
                else
                    songs = rep.GetSongsByKeywords(query);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                throw new HttpResponseException(ex.Message, HttpStatusCode.InternalServerError);
            }

            if (songs == null)  // No songs found
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            return songs;
        }

        // Upload song
        public HttpResponseMessage Post()
        {
            // Verify that this is an HTML Form file upload request
            if (!Request.Content.IsMimeMultipartContent("form-data"))
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            String songsPath = HttpContext.Current.Server.MapPath("~/Content/Songs/");

            var files = HttpContext.Current.Request.Files;
            foreach (var item in files.AllKeys)
            {
                var postedFile = files[item];
         
                postedFile.SaveAs(songsPath + postedFile.FileName);

                // Read information from mp3 file:
                TagLib.File tagFile = TagLib.File.Create(songsPath + postedFile.FileName);
                
                Debug.WriteLine("Added File: Title: " + tagFile.Tag.Title + " Artist: " + tagFile.Tag.FirstPerformer + 
                                " Genre: " + tagFile.Tag.FirstGenre);

                // Create the song object:
                Song song = new Song();
                if (tagFile.Tag.Title == null | tagFile.Tag.Title == "")
                    song.Name = "Unknown";
                else
                    song.Name = tagFile.Tag.Title;

                if (tagFile.Tag.FirstPerformer == null | tagFile.Tag.FirstPerformer == "")
                    song.Artist = "Unknown";
                else
                    song.Artist = tagFile.Tag.FirstPerformer;

                song.Genre = tagFile.Tag.FirstGenre;
                song.Src = "/Content/Songs/" + postedFile.FileName;

                try
                {
                    rep.AddSong(song);  // Add to database
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    throw new HttpResponseException(ex.Message, HttpStatusCode.InternalServerError);
                }
            }

            return new HttpResponseMessage(HttpStatusCode.Created);
        }
    }
}
